package com.smartinput.config

import com.smartinput.websocket.SmartInputWebSocketHandler
import com.smartinput.websocket.WebSocketAuthInterceptor
import com.smartinput.voice.websocket.VoiceWebSocketHandler
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.web.socket.config.annotation.EnableWebSocket
import org.springframework.web.socket.config.annotation.WebSocketConfigurer
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry

@Configuration
@EnableWebSocket
class WebSocketConfig : WebSocketConfigurer {
    
    @Autowired
    private lateinit var smartInputWebSocketHandler: SmartInputWebSocketHandler
    
    @Autowired
    private lateinit var webSocketAuthInterceptor: WebSocketAuthInterceptor
    
    @Autowired
    private lateinit var voiceWebSocketHandler: VoiceWebSocketHandler
    
    @Value("\${app.websocket.allowed-origins}")
    private lateinit var allowedOrigins: String
    
    override fun registerWebSocketHandlers(registry: WebSocketHandlerRegistry) {
        // 解析允许的源
        val origins = allowedOrigins.split(",").map { it.trim() }
        
        // 需要认证的 WebSocket 端点
        registry.addHandler(smartInputWebSocketHandler, "/ws/auth")
            .addInterceptors(webSocketAuthInterceptor)
            .setAllowedOriginPatterns(*origins.toTypedArray())
        
        // 不需要认证的 WebSocket 端点（用于设备连接）
        registry.addHandler(smartInputWebSocketHandler, "/ws")
            .setAllowedOriginPatterns(*origins.toTypedArray())
        
        // 添加设备特定的 WebSocket 端点，需要认证
        registry.addHandler(smartInputWebSocketHandler, "/ws/{deviceId}")
            .addInterceptors(webSocketAuthInterceptor)
            .setAllowedOriginPatterns(*origins.toTypedArray())
        
        // 语音识别 WebSocket 端点
        registry.addHandler(voiceWebSocketHandler, "/ws/voice")
            .setAllowedOriginPatterns(*origins.toTypedArray())
    }
}